package com.qd.panda.gas.station.ejiayou.util;

import com.qd.panda.gas.station.ejiayou.config.EGasConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 针对易加油的签名
 *
 * @author sjk
 * @create 2023-02-09 15:59
 * @since 1.0.0
 */
@Service
@Slf4j
public class EGasSignUtil {
    private static EGasConfig eGasConfig;

    @Autowired
    public EGasSignUtil(EGasConfig eGasConfig) {
        EGasSignUtil.eGasConfig = eGasConfig;
    }


    public static String sign(Map<String,Object> params,String timestamp) {
        StringBuilder linkString = createLinkString(params);
        log.info("linkString = " + linkString);
        String str = linkString.append("&timestamp=").append(timestamp)
                .append("&beforeKey=").append(eGasConfig.getBeforeKey())
                .append("&afterKey=").append(eGasConfig.getAfterKey()).toString();
        log.info("str = " + str);
        String sign = DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8)).toUpperCase();
        log.info("sign = " + sign);
        return sign;
    }

    /**
     * 订单支付和订单退款回执信息生成签名
     * @param params 参数
     * @return md5以后的值
     */
    public static String sign(Map<String,Object> params) {
        StringBuilder linkString = createLinkString(params);
        log.info("linkString = " + linkString);
        String str = linkString.append("&").append(eGasConfig.getSk()).toString();
        log.info("str = " + str);
        String sign = DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8));
        log.info("sign = " + sign);
        return sign;
    }

    public static String sign(String timestamp) {
        String str =  "timestamp=" + timestamp +
                "&beforeKey=" + eGasConfig.getBeforeKey() +
                "&afterKey=" + eGasConfig.getAfterKey();
        return DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8)).toUpperCase();
    }


    private static StringBuilder createLinkString(Map<String, Object> params) {

        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuilder preStr = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = String.valueOf(params.get(key));
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                preStr.append(key).append("=").append(value);
            } else {
                preStr.append(key).append("=").append(value).append("&");
            }
        }
        return preStr;
    }
}